<?php

namespace Api\Event;

use Think\Log;

/** 
 * 积分策略
 * @author Legend. <xcx_legender@qq.com>
 * @param 
 * @return 
 */

class ScoreEvent extends BaseEvent 
{
	// limit  max  score
	protected $options = [
		// 首次注册
		'register' => ['function' => 'new','limit' => 1, 'memo' => '注册', 'score' => 100],
		// 设置资料到70%
		'profile'  => ['function' => 'new','limit' => 1, 'memo' => '完善资料'],
		// 首次设置头像
		'avatar'   => ['function' => 'new','limit' => 1, 'memo' => '首次设置头像'],
		// 首次设置背景
		'bg'       => ['function' => 'new','limit' => 1, 'memo' => '首次设置背景'],
		// 首次设置语音
		'sound'    => ['function' => 'new','limit' => 1, 'memo' => '首次设置语音'],

		// 待商城功能上线时开启 liubo 2016-8-3
		// 首次绑定邮箱
		'mail_verify'  => ['function' => 'new','limit' => 1, 'memo' => '首次绑定邮箱', 'score' => 50],
		// 首次设置支付密码
		'pay_password' => ['function' => 'new','limit' => 1, 'memo' => '首次设置支付密码', 'score' => 50],

		// 签到
		// 'sign'     => ['function' => 'sign', 'limit'=> 1, 'memo' => '签到'],
		'login'     => ['function' => 'daily', 'limit'=> 1, 'memo' => '登录'],
		// 评论
		'comments' => ['function' => 'daily', 'limit'=> 5, 'memo' => '评论视频'],
		'zan' 	   => ['function' => 'daily', 'limit'=> 10, 'memo' => '点赞'],
		'share'    => ['function' => 'daily', 'limit'=> 10, 'memo' => '分享', 'score' => 1],
		// ...
	];

	protected $actions;

	public function __construct()
	{
		parent::__construct();
		// 获取积分策略配置
		//
		$config = C('');
		foreach ($this->options as $key => &$value) {
			$k_option = $config['score.'.$key];

			$this->formatOption($value, $k_option);
		}
		$this->actions = array_keys($this->options);
	}

	protected function formatOption(&$option, $k_option)
	{
		$format = [];
		$format = explode("\r\n", $k_option);
		$data  = [];
		switch ($format[0]) {
			case '[level]':
				if ($option['function'] != 'sign') return;
				$count = count($format);
				for ($i=1; $i < $count; $i++) { 
					$temp = explode(':', $format[$i]);
					$key = $temp[0];
					$range = explode('-', $key);
					if ($key{0} == '>')
					{
						$data['score']['>'] = [(int)substr($key, 1), $temp[1]];
					}
					elseif ($key{0} == '<')
					{
						$data['score']['<'] = [(int)substr($key, 1), $temp[1]];
					}
					elseif (count($range) > 1)
					{
						if ($range[0] == $range[1])
						{
							return;
						}
						foreach (range($range[0], $range[1]) as $value) {
							$data['score'][$value] = $temp[1];
						}
					}
					else
					{
						$data['score'][$key] = $temp[1];
					}
				}
				break;
			case '[daily]':
				if ($option['function'] != 'daily') return;
				$daily = explode('|', $format[1]);
				if ($daily[1])
				{
					$limit = explode(':', $daily[1]);
					if ($limit[0] == 'limit' && intval($limit[1]) > 0)
					{
						$data['limit'] = $limit[1];
					}
				}
				$data['score'] = $daily[0];
				break;
			default:
				if (intval($format[0]) > 0)
				{
					$data['score'] = $format[0];
				}
				break;
		}
		if ($data) $option = array_merge($option, $data);
	}


	/** 
	 * 直接设置用户的积分
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	
	public function set_score($uid, $action, $score, $memo)
	{
		
	}

	/** 
	 * 获取到一个积分
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	
	public function get($uid, $action, $target_id = 0)
	{
		$uid = (int)$uid;
		if (!in_array($action, $this->actions))
		{
			return false;
		}
		$options = $this->options[$action];
		$func = 'get_'.$options['function'];
		if (!method_exists($this, $func))
		{
			return false;
		}
		$res = $this->$func($uid, $action, $options);
		if ($res !== false)
		{
			$score = $res['score'];
			$res = event('User')->score_oper($uid, $score, $action, $res['memo'], $target_id);
			if ($res !== false) {
		        $params = [
		            'uid' => $uid,
		            'money' => $score,
		            'task_type' => $options['function'],
		            'task_name' => $action,
		            'task_id'   => $target_id,
		        ];
		        $response = event('LocalClient')->doRequest('add_coin', $params);
			}
			return $score;
		}
		return false;
	}

	protected function formatMemo($options, $score)
	{
		return $options['memo'].',获得⑥币'.$score;
	}

	/** 
	 * 判断一次性的数据
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	
	protected function get_new($uid, $action, $options = [])
	{
		$score = $options['score'] ?: 0;
		$map = [
			'uid'     => $uid,
			'action'  => $action
		];
		$res = service('UserMissionLog')->where($map)->count();
		if ($res || $score <= 0)
		{
			return false;
		}
		$data = [
			'score' => $score,
			'memo'  => $this->formatMemo($options, $score)
		];
		return $data;
	}

	/** 
	 * 判断签到的数据
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	protected function get_sign($uid, $action, $options = [])
	{
		$map = [
			'uid'     => $uid,
			'action'  => $action,
			'date'    => date('Y-m-d', NOW_TIME)
		];
		$res = service('UserMissionLog')->where($map)->count();
		if ($res)
		{
			return false;
		}
		$score = $this->get_sign_score($uid);
		$data = [
			'score' => $score,
			'memo'  => $this->formatMemo($options, $score)
		];
		return $data;
	}


	/** 
	 * 签到的积分
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	
	protected function get_sign_score($uid)
	{
		return 5;
	}


	/** 
	 * 判断每日的数据
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	
	protected function get_daily($uid, $action, $options = [])
	{
		$score = $options['score'] ?: 0;
		$map = [
			'uid'     => $uid,
			'action'  => $action,
			'date'    => date('Y-m-d', NOW_TIME)
		];
		$limit = $options['limit'];
		$res = service('UserMissionLog')->where($map)->count();
		if (($limit > 0 && $limit <= $res) || !$score)
		{
			return false;
		}
		$data = [
			'score' => $score,
			'memo'  => $this->formatMemo($options, $score)
		];
		return $data;
	}


	/** 
	 * 使用一个积分
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	
	public function use_score()
	{
		
	}

	public function dailyTask($uid)
	{
		$list = [];
		foreach ($this->options as $key => $value) {
			if ($key == 'register') {
				continue;
			}
			$map = [
				'uid'     => $uid,
				'action'  => $key,
			];
			if ($value['function'] != 'new') {
				$map['date'] = date('Y-m-d', NOW_TIME);
			}
			$limit = $value['limit'];

			$res = service('UserMissionLog')->where($map)->count();

			$status = ($res && $limit <= $res) ? 1 : 0;
			if ($value['function'] == 'new') {
				$list['news'][] = [
					'status'  => $status,
					'content' => $value['memo'],
					'coin'   => intval($value['score']),
				];
			} else {
				$list['daily'][] = [
					'status'  => $status,
					'content' => $value['memo'],
					'coin'   => intval($value['score']),
					'limit'   => intval($limit),
				];
			}
		}

		return $list;
	}



}